/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.view;

import ru.ssau.lib.GBC;
import ru.ssau.lib.AdvancedJComboBox;
import ru.ssau.lib.DateSetPanel;
import ru.ssau.lib.StringIntegerPair;
import ru.ssau.lib.InvalidDateException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import ru.ssau.entities.Message;


public class MessageDialog extends JDialog {

    private JTextField captionField;
    private JTextArea textArea;
    private AdvancedJComboBox usersComboBox;
    private AdvancedJComboBox threadsComboBox;
    private DateSetPanel datePanel;

    private JButton okButton;
    private JButton cancelButton;

    private Message message;

    public MessageDialog(Frame parent) {
        super(parent, "Add/edit message", true);
        usersComboBox = new AdvancedJComboBox();
        threadsComboBox = new AdvancedJComboBox();

        initComponents();
        layoutComponents();

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                message = null;
                setVisible(false);
            }
        });

        pack();
        setMinimumSize(getPreferredSize());
    }

    private void initComponents() {
        okButton = new JButton("OK");
        okButton.addActionListener(new OkAction());
        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new CancelAction());

        captionField = new JTextField(10);
        textArea = new JTextArea(3,20);
        textArea.setLineWrap(true);
        datePanel = new DateSetPanel();
    }

    private void layoutComponents() {
        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        
        JPanel messagePanel = new JPanel(new GridBagLayout());
        add(messagePanel);
        Border border = BorderFactory.createEtchedBorder();
        messagePanel.setBorder(BorderFactory.createTitledBorder(border, "Add/edit message"));

        JLabel caption = new JLabel("Caption:", JLabel.RIGHT);
        messagePanel.add(caption, new GBC(0,0).setInsets(0,5,3,5));
        messagePanel.add(captionField, new GBC(1,0,2,1).setInsets(0,5,0,5));
        JLabel user = new JLabel("User:", JLabel.RIGHT);
        messagePanel.add(user, new GBC(0,1).setInsets(0,0,3,5));
        messagePanel.add(usersComboBox, new GBC(1,1).setInsets(0,0,0,5).setFill(GBC.HORIZONTAL).setWeight(50,0));
        JLabel thread = new JLabel("Thread:", JLabel.RIGHT);
        messagePanel.add(thread, new GBC(2,1).setInsets(0,0,0,5));
        messagePanel.add(threadsComboBox, new GBC(3,1).setInsets(0,0,0,5).setFill(GBC.HORIZONTAL).setWeight(50,0));
        messagePanel.add(datePanel, new GBC(0,2,4,3).setFill(GBC.BOTH));
        JLabel text = new JLabel("Text:", JLabel.RIGHT);
        messagePanel.add(text, new GBC(0,5).setInsets(0,0,3,5));
        messagePanel.add(new JScrollPane(textArea), new GBC(1,5,3,2).setInsets(0,2,0,5).setFill(GBC.BOTH));

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel);
    }

    public Message showDialog(Message aMessage, Object[] users, Object[] threads) {
        usersComboBox.setItems(users);
        threadsComboBox.setItems(threads);

        message = aMessage;
        if(message == null) {
            message = new Message();
        }
        //Установка выбранных значений в списках пользователей и тредов
        if(message.getUserId() != null) {
            for(Object obj: users) {
                StringIntegerPair user = (StringIntegerPair) obj;
                if(user.getNumber().equals(message.getUserId())) {
                    usersComboBox.setSelectedItem(user);
                    break;
                }
                
            }
        }
        for(Object obj: threads) {
            StringIntegerPair thread = (StringIntegerPair) obj;
            if(thread.getNumber().equals(message.getThreadId())) {
                threadsComboBox.setSelectedItem(thread);
                break;
            }
        }

        captionField.setText(message.getCaption());
        textArea.setText(message.getText());
        datePanel.setDate(message.getPostDate());

        captionField.grabFocus();
        setVisible(true);
        return message;
    }

    private class OkAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                StringIntegerPair user = (StringIntegerPair) usersComboBox.getSelectedItem();
                if(user == null)
                    throw new InvalidFieldValueException("No user choosen");

                StringIntegerPair thread = (StringIntegerPair) threadsComboBox.getSelectedItem();
                if(thread == null)
                    throw new InvalidFieldValueException("No thread choosen");

                if(captionField.getText().trim().equals(""))
                    throw new InvalidFieldValueException("Caption field is empty");
                
                if(textArea.getText().trim().equals(""))
                    throw new InvalidFieldValueException("Text field is empty");
                
                message.setPostDate(datePanel.getDate());
                message.setUserId(user.getNumber());
                message.setThreadId(thread.getNumber());
                message.setCaption(captionField.getText());
                message.setText(textArea.getText());
                setVisible(false);
            } catch(InvalidDateException exception) {
                JOptionPane.showMessageDialog(MessageDialog.this, exception.getMessage(), "Input error", JOptionPane.ERROR_MESSAGE);
            } catch(InvalidFieldValueException exception) {
                JOptionPane.showMessageDialog(MessageDialog.this, exception.getMessage(), "Input error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private class CancelAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            message = null;
            setVisible(false);
        }
    }
}
